package day11.gec.preparestatement;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import org.junit.Test;

public class CUDDemo3 {
	
	@Test
	public void testAdd() {
		String sql = "insert into t_user(name,password)values(?,?)";
		try(
			Connection conn = DriverManager.getConnection("jdbc:mysql:///hrm", "root", "root");
			PreparedStatement st = conn.prepareStatement(sql);
			){
			//给问号设置值
			st.setString(1, "tom");
			st.setString(2, "222");
			
			//执行语句 
			st.executeUpdate();//不要传sql进来 
			
			System.out.println("添加成功...");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void testUpdate() {
		String sql = "update t_user set name = ?,password=? where id = ?";
		try(
			Connection conn = DriverManager.getConnection("jdbc:mysql:///hrm", "root", "root");
			PreparedStatement st = conn.prepareStatement(sql);
			){
			//给问号设置值
			st.setString(1, "tom 张");
			st.setString(2, "888");
			st.setInt(3, 3);
			
			//执行语句 
			st.executeUpdate();//不要传sql进来 
			
			//打印sql
			System.out.println(st);
			
			System.out.println("修改成功...");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void testDel() {
		String sql = "delete from t_user where id = ?";
		try(
			Connection conn = DriverManager.getConnection("jdbc:mysql:///hrm","root", "root");
			PreparedStatement st = conn.prepareStatement(sql);
			){
			//给问号设置值
			st.setInt(1, 2);
			//执行语句 
			st.executeUpdate();// 执行ddl dml 
			
			//执行打印的sql
			System.out.println("sql:" + st);
			
			System.out.println("删除成功....");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
